<template>
<view class="uni-body">



<!-- 首次进入引导添加到“我的小程序” -->
<!--view class="addMyMiniapp" v-if="isFirst" @tap.stop="shutAddMyMiniapp">
	<view>点击加入我的小程序 ↑</view>
	<text>了解"{{webSiteName}}"最新文章</text>
</view-->
	<!-- 头部组件 -->
	<toubu :src="www['logo']" />
	<!-- 轮播图 -->
	<view :style="'display:' + displaySwiper">
		<swiper :style="{height: swiperheight + 'px'}" class="d-waikuang-10 d-yuanjiao-10"  interval="10000" autoplay="true" indicator-color="rgba(0, 0, 0, .1)" indicator-active-color="rgba(0, 0, 0, .6)">
			<block v-for="(item, index) in postsShowSwiperList" :key="index">
				<swiper-item class="swiper-item" :id="item.id" :index="index" :data-redicttype="item.type" :data-appid="item.appid" :data-url="item.url" @tap="redictDetail">
					<view class="swiper-item-wrap">
						<image  mode="aspectFill" :src="item.thumb" class="d-yuanjiao-10 swiper-item-img" style=""></image>
					</view>
					<!--view class="swiper-mask"></view-->
					<!--view class="swiper-desc">
						<text>{{item.title}}</text>
					</view-->
				</swiper-item>
			</block>
		</swiper>
	</view>
	<view class="d-clear"></view>
	<!-- 图标 -->
	<view class="d-waikuang-10">
		<view class="d-kuan d-beijing-bai d-yuanjiao-10" :style="'display:' + displaySwiper">
			<block v-for="(item, index) in tubiaoList" :key="index">
				<view v-if="item.catid == 3" class="d-baifen-25 d-zuo d-neirong-juzhong d-shangxia-10">
					<image mode="aspectFill" :src="item.thumb" class="d-yuanjiao-10 d-img-50" ></image>
					<view class="d-ziti-12 d-xia-6">{{item.title}}</view>
					<view class="d-clear"></view>
				</view>
				
			</block>
			<view class="d-clear"></view>
		</view>
	</view>
	<!-- 列表template模板 -->
	<view class="d-kuan">
		<block data-type="template" data-is="tempCommonList" data-attr="postsList:postsList,listAdsuccess:listAdsuccess">
			<block v-for="(item, index) in postsList" :key="index">
				<view class="d-kuan">
					<view class="d-waikuang-10">
						<view class="d-kuan d-beijing-bai d-yuanjiao-10">
							<view class="d-neikuang-10 d-buhuanhang">
								<!--头像-->
								<view class="d-gaokuang-40 d-kuanggao-40 d-yuanjiao-40 ">
									<image v-if="item.touxiang" :src="item.touxiang" mode="aspectFill" class="d-img-40 d-yuanjiao-50 d-beijing-hui"></image>
									<image v-else src="/static/assets/images/avatar.png" mode="aspectFill" class="d-img-40 d-yuanjiao-50 d-beijing-hui"></image>
								</view>
								<view class="d-kuan d-zuo-10">
									<view class="d-wenzi-14 d-jiacu">{{item.mingcheng}}</view>
									<view class="d-wenzi-14 d-wenzi-yanse-hui">{{item.yonghuzu}}. {{item.guishudi}}</view>
								</view>
								<view class="d-kuan-80 d-neirong-you" >
									<view class="d-kuan-40 d-beijing-hui d-neikuang-zuoyou-2-shangxia-4 d-wenzi-12 d-yuanjiao-50 d-neirong-juzhong" >关 注</view>
								</view>
							</view>
							<view class="d-zuoyou-neikuang-10">
								<!--标题-->
								<view v-if="item.title" class="d-jiacu d-wenzi-16 d-xia-10">{{item.title}}</view>
								<view class=" d-wenzi-14 d-wenzi-huanhang d-wenzi-yanse-hui">
									{{item.neirong}}
								</view>
								<!--评论-->
								<view class="d-shangxia-neikuang-10">
									<view class="d-wenzi-12 d-kuan-baifen-50 d-zuo d-wenzi-yanse-hui">
										{{item.shijian}}
									</view>
									<view class="d-wenzi-12 d-kuan-baifen-50 d-zuo d-wenzi-yanse-hui">
										<view class="d-wenzi-12 d-kuan-baifen-50 d-zuo d-neirong-zuo d-buhuanhang">
											<image src="/static/images/img/xiaoxi3.png" mode="aspectFill" class="d-img-20 "></image>
											<text class="d-kuan-100 d-wenzi-yanse-hui d-shang-2">{{item.comments}}</text>
										</view>
										<view class="d-wenzi-12 d-kuan-baifen-50 d-zuo d-neirong-you  ">
											<!--text class="d-kuan-100 d-hanggao-30 d-wenzi-yanse-hui">0</text-->
											<image src="/static/images/img/zan3.png" mode="aspectFill" class="d-img-20 "></image>
											
										</view>
									</view>
									<view class="d-clear"></view>
								</view>
								
							</view>
						</view>
						<!--评论-->
						<view class="">
							
						</view>
					</view>
				</view>
			</block>
		</block>
		<view :style="'display:' + (isLoading?'block':'none')">
			<template is="tempLoading"></template>
		</view>
		<view class="loadingmore" :style="'display:' + floatDisplay">
			<view class="no-more" :hidden="!isLastPage">- 无更多文章 -</view>
		</view>
		<!-- 版权信息template模板 -->
		<view class="copyright" :style="'display:' + floatDisplay">
			<block data-type="template" data-is="tempCopyright" data-attr="webSiteName:webSiteName,domain:domain">
				<view> {{webSiteName}}</view>
			</block>
		</view>
	</view>
	<!-- 列表template模板 -->
	<!--view :style="'display:' + showallDisplay">
		<view class="container">
			<block data-type="template" data-is="tempCommonList" data-attr="postsList:postsList,listAdsuccess:listAdsuccess">
					<view class="post-list">
						<block v-for="(item, index) in postsList" :key="index">
							<view class="list-item-ad" :index="index" v-if="index%item.listAdEvery ==0  && index!=0 && item.listAd =='1' && item.listAdId !=''  && listAdsuccess">
								<block v-if="(index/item.listAdEvery)%2==0">
								<ad :unit-id="item.videoAdId" ad-type="video" ad-theme="white" @error="adbinderror"></ad>
								</block>
								<block v-else>
								<ad :unit-id="item.listAdId" ad-intervals="30" @error="adbinderror"></ad>
								</block>
							</view>
							<view class="post-item" :index="index" :id="item.id" @tap="redictDetail">
								<image :src="item.thumb" mode="aspectFill" class="post-img"></image>
								<view class="post-desc">
									<view class="post-title">
									<text>{{item.title}}</text>
									</view>
									<view class="post-data">
										<image src="/static/images/calendar.png"></image>
										<text>{{item.updatetime}}</text>

										<image src="/static/images/pageviews.png"></image>
										<text class>{{item.hits}}</text>
									</view>
								</view>
							</view>
						</block>
					</view>
			</block>
			<view :style="'display:' + (isLoading?'block':'none')">
				<template is="tempLoading"></template>
			</view>
			<view class="loadingmore" :style="'display:' + floatDisplay">
				<view class="no-more" :hidden="!isLastPage">- 无更多文章 -</view>
			</view>
			<view class="copyright" :style="'display:' + floatDisplay">
				<block data-type="template" data-is="tempCopyright" data-attr="webSiteName:webSiteName,domain:domain">
					<view> {{webSiteName}}</view>
				</block>
			</view>
		</view>
	</view-->

	<!-- 无法访问网络 -->
	<view class="showerror" :style="'display:' + showerror">
		<!--image src="/static/images/cry80.png" style="height:100rpx;width:100rpx"></image-->
		<view class="errortext">
			暂时无法访问网络，下拉重试...
		</view>
	</view>
</view>
</template>

<script>
import toubu from "@/components/toubu/toubu";  //引入组件
var Api = require("../../utils/api.js");
var util = require("../../utils/util.js");

var wxApi = require("../../utils/wxApi.js");
var wxRequest = require("../../utils/wxRequest.js");
import config from "../../utils/config";
var pageCount = config.getPageCount;
var webSiteName = config.getWebsiteName;
var domain = config.getDomain;
var topNav = config.getIndexNav;

export default {
  data() {
    return {
      postsList: [],
	  tubiaoList: [],
      postsShowSwiperList: [],
      isLastPage: false,
      page: 1,
	  swiperheight: '',
	  swiperItemHeight: '',
      search: '',
      categories: 0,
      showerror: "none",
      showCategoryName: "",
      categoryName: "",
      showallDisplay: "block",
      displayHeader: "none",
      displaySwiper: "none",
      floatDisplay: "none",
      displayfirstSwiper: "none",
      topNav: topNav,
      webSiteName: webSiteName,
      domain: domain,
      isFirst: false,
      // 是否第一次打开,
      isLoading: false,
	  www: [],
    };
  },
	mounted() {
		
	},


  components: {
	  toubu,
  },
  props: {},
  onShareAppMessage: function () {
    return {
      title: '“' + webSiteName + '”小程序',
      path: 'pages/index/index',
      success: function (res) {// 转发成功
      },
      fail: function (res) {// 转发失败
      }
    };
  },
  onPullDownRefresh: function () {
    var self = this;
    self.setData({
      showerror: "none",
      showallDisplay: "block",
      displaySwiper: "none",
      floatDisplay: "none",
      isLastPage: false,
      page: 1,
      postsShowSwiperList: []
    });
    this.fetchTopFivePosts();
	this.tubiaoPosts();

    this.fetchPostsData(self);
  },
  onReachBottom: function () {
    var self = this;
    if (!self.isLastPage) {
      self.setData({
        page: self.page + 1
      });
      console.log('当前页' + self.page);
      this.fetchPostsData(self);
    } else {
      console.log('最后一页');
    }
  },
  onLoad: function (options) {
	this.tubiaoPosts();
	this.getWww();
	this.$nextTick(() => {
		//this.getGao();
	});
	
    var self = this;
    self.fetchTopFivePosts();
	
    self.fetchPostsData(self); // 判断用户是不是第一次打开，弹出添加到我的小程序提示

    var isFirstStorage = wx.getStorageSync('isFirst'); // console.log(isFirstStorage);

    if (!isFirstStorage) {
      self.setData({
        isFirst: true
      });
      wx.setStorageSync('isFirst', 'no'); // console.log(wx.getStorageSync('isFirst'));
      setTimeout(function () {
        self.setData({
          isFirst: false
        });
      }, 5000);
    }
  },
	onReady() {
		this.$nextTick(() => {
		uni.createSelectorQuery().in(this).select('.swiper-item-img').boundingClientRect(data => {
		console.log(data)
		}).exec()
		});
	},

  onShow() {
	
	this.$nextTick(() => {
		this.getGao();
	});
    wx.setStorageSync('openLinkCount', 0);
    var nowDate = new Date();
    nowDate = nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + '-' + nowDate.getDate();
    nowDate = new Date(nowDate).getTime();
  },
    methods: {
		getWww() {
			var self = this;
			self.setData({
			  www: []
			});
			var getTubiaoRequest = wxRequest.getRequest(Api.getWwwUrl());
			getTubiaoRequest.then(response => {
				if (response.data.code == 1) {
				  //console.log(response.data.data); 
				  self.www = response.data.data
				} else {
				  self.setData({
					displaySwiper: "none"
				  });
				}
			});
		},
		//获取图标列表
		tubiaoPosts() {
			var self = this; 
			self.setData({
			  tubiaoList: []
			});
			var getTubiaoRequest = wxRequest.getRequest(Api.getTubiaoUrl());
			getTubiaoRequest.then(response => {
				if (response.data.code == 1) {
				  //console.log(response.data.data); 
				  self.tubiaoList = response.data.data
				} else {
				  self.setData({
					displaySwiper: "none"
				  });
				}
			});
		},


		getGao() {
			// 判断海报高度
			uni.getSystemInfo({
				success: (res) => {
					let info = uni.createSelectorQuery().in(this).select(".swiper-item");
					info.boundingClientRect(data => {
						//console.log(data)
						this.swiperheight = 150
					}).exec();
				}
			});
			/*uni.getSystemInfo({
				success: (res) => {
					let info = uni.createSelectorQuery().in(this).select(".swiper-item");
					info.boundingClientRect().exec(res => {
			                console.log(res)  // 元素高度
							//this.swiperHeight = res[0].height; // 返回的值可以用作动态修改swiper高度
					});
				}
			});*/
			
		},

		formSubmit: function (e) {
		  var url = '../list/list';
		  var key = '';
			 //console.log('earch');
			  if (e.currentTarget.id == "search-input") {
				key = e.detail.value;
			  } else {
				key = e.detail.value.input;
			  }

			  if (key != '') {
				url = url + '?search=' + key;
				wx.navigateTo({
				  url: url
				});
			  } else {
				wx.showModal({
				  title: '提示',
				  content: '请输入内容',
				  showCancel: false
				});
			  }
		},
		
		fetchTopFivePosts: function () {
		  var self = this; //获取滑动图片的文章
		  var getPostsRequest = wxRequest.getRequest(Api.getSwiperUrl());
		  getPostsRequest.then(response => {
			
			if (response.data.code == 1) {
			  self.setData({
				postsShowSwiperList: self.postsShowSwiperList.concat(response.data.data.map(function (item) {
				  if (!item.thumb) {
					item.thumb = "/static/images/logo700.png";
				  }
				  item.redicttype = 'apppage';
				  item.url = '../detail/detail?id=' + item.id;
				  return item;
				})),
				displaySwiper: "block"
			  });
			} else {
			  self.setData({
				displaySwiper: "none"
			  });
			}
		  }).catch(function (response) {
			//console.log(response);
			self.setData({
			  showerror: "block",
			  floatDisplay: "none"
			});
		  }).finally(function () {});
		},
		//获取列表数据
		fetchPostsData: function (data) {
		  var self = this;
		  if (!data) data = {};
		  if (!data.page) data.page = 1;
		  if (!data.categories) data.categories = 0;
		  if (!data.search) data.search = '';

		  if (data.page === 1) {
			self.setData({
			  postsList: []
			});
		  }

		  ;
		  self.setData({
			isLoading: true
		  });
	  

			var getPostsRequest = wxRequest.getRequest(Api.getQuanindexUrl(data));
			getPostsRequest.then(response => {
				//console.log(response.data.data);
			if (response.data.code == 1) {
				if (response.data.data.length) {
				  if (response.data.data.length < pageCount) {
					self.setData({
					  isLastPage: true,
					  isLoading: false
					});
				  }

				  self.setData({
					floatDisplay: "block",
					postsList: self.postsList.concat(response.data.data.map(function (item) {
				
					  if (item.thumb == null || item.thumb == '') {
						item.thumb = "/static/images/logo700.png";
					  }

					  return item;
					}))
				  });
				} else {
				  if (response.data.code == "rest_post_invalid_page_number") {
					self.setData({
					  isLastPage: true,
					  isLoading: false
					});
					wx.showToast({
					  title: '没有更多内容',
					  mask: false,
					  duration: 1500
					});
				  } else {
					  // 隐藏提示
					/*wx.showToast({
					  title: response.data.message,
					  duration: 1500
					});*/
					wx.showToast({
					  title: '没有更多内容',
					  duration: 500
					});
				  }
				}
			  }
			}).catch(function (response) {
			  if (data.page == 1) {
				self.setData({
				  showerror: "block",
				  floatDisplay: "none"
				});
			  } else {
				wx.showModal({
				  title: '加载失败',
				  content: '加载数据失败,请重试.',
				  showCancel: false
				});
				self.setData({
				  page: data.page - 1
				});
			  }
			}).finally(function (response) {
			  wx.hideLoading();
			  self.setData({
				isLoading: false
			  });
			  wx.stopPullDownRefresh();
			});
		},
		//加载分页
		loadMore: function (e) {
		  var self = this;

		  if (!self.isLastPage) {
			self.setData({
			  page: self.page + 1
			}); //console.log('当前页' + self.data.page);

			this.fetchPostsData(self);
		  } else {
			wx.showToast({
			  title: '没有更多内容',
			  mask: false,
			  duration: 1000
			});
		  }
		},
		// 跳转至查看文章详情
		redictDetail: function (e) {
		  // console.log('查看文章');
		  var id = e.currentTarget.id,
			  url = '../detail/detail?id=' + id;
		  wx.navigateTo({
			url: url
		  });
		},
		//首页图标跳转
		onNavRedirect: function (e) {
		  var redicttype = e.currentTarget.dataset.redicttype;
		  var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
		  var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;
		  var extraData = e.currentTarget.dataset.extraData == null ? '' : e.currentTarget.dataset.extraData;

		  if (redicttype == 'apppage') {
			//跳转到小程序内部页面         
			wx.navigateTo({
			  url: url
			});
		  } else if (redicttype == 'webpage') //跳转到web-view内嵌的页面
			{
			  url = '../webpage/webpage?url=' + url;
			  wx.navigateTo({
				url: url
			  });
			} else if (redicttype == 'miniapp') //跳转到其他app
			{
			  wx.navigateToMiniProgram({
				appId: appid,
				envVersion: 'release',
				path: url,
				extraData: extraData,

				success(res) {// 打开成功
				},

				fail: function (res) {
				  console.log(res);
				}
			  });
			}
		},
		// 跳转至查看小程序列表页面或文章详情页
		redictAppDetail: function (e) {
		  // console.log('查看文章');
		  var id = e.currentTarget.id;
		  var redicttype = e.currentTarget.dataset.redicttype;
		  var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url;
		  var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid;

		  if (redicttype == 'detailpage') //跳转到内容页
			{
			  url = '../detail/detail?id=' + id;
			  wx.navigateTo({
				url: url
			  });
			}

		  if (redicttype == 'apppage') {
			//跳转到小程序内部页面         
			wx.navigateTo({
			  url: url
			});
		  } else if (redicttype == 'webpage') //跳转到web-view内嵌的页面
			{
			  url = '../webpage/webpage?url=' + url;
			  wx.navigateTo({
				url: url
			  });
			} else if (redicttype == 'miniapp') //跳转到其他app
			{
			  wx.navigateToMiniProgram({
				appId: appid,
				envVersion: 'release',
				path: url,

				success(res) {// 打开成功
				},

				fail: function (res) {
				  console.log(res);
				}
			  });
			}
		},
		//返回首页
		redictHome: function (e) {
		  //console.log('查看某类别下的文章');  
		  var id = e.currentTarget.dataset.id,
			  url = '/pages/index/index';
		  wx.switchTab({
			url: url
		  });
		},
		
    },
	computed: {
		
	},

};
</script>
<style>
@import "./index.css";
page {
	background-color: #f3f4f7;
}
</style>